/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/';
import router from '@/router/router'
import {
    serialize
} from '@/util/util'
import {
    getToken
} from '@/util/auth'
import {
    Message
} from 'element-ui'
import website from '@/config/website';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { catUrl,ddUrl } from '@/config/env'
// import {
//     delete
// } from 'vue/types/umd';
axios.defaults.timeout = 10000;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
    showSpinner: false
});
//HTTPrequest拦截
axios.interceptors.request.use(async config => {
    NProgress.start() // start progress bar
    if (getToken()) {
        config.headers.token = getToken()
    }
    // config.headers["Content-type"] = 'application/x-www-form-urlencoded';
    return config
}, error => {
    return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
    NProgress.done();
    const status = Number(res.status) || 200;
    const statusWhiteList = website.statusWhiteList || [];
    const message = res.data.message;
    const code = res.data.code
    //如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res);
    //如果是401则跳转到登录页面
    if (status === 401) store.dispatch('FedLogOut').then(() => router.push({
        path: '/login'
    }));
    if (res.request.responseURL.includes(catUrl)||res.request.responseURL.includes(ddUrl)) {
        if (message) {
            Message({
                message: message,
                type: code == 1 ? 'success' : 'error'
            })
        }
    }


    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
        Message({
            message: message || "服务器异常",
            type: 'error'
        })
        return Promise.reject(new Error(message))
    }
    return res;
}, error => {
    NProgress.done();
    return Promise.reject(new Error(error));
})

export default axios;